<template>
  <el-dialog :visible.sync="dialog" :title="is_edit ? '编辑用户' : '新增用户'" append-to-body width="570px">
    <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="66px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" :disabled="is_edit" maxlength="10" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!is_edit">
        <el-input v-model="form.password" type="password" :disabled="is_edit" placeholder="请输入密码" maxlength="20" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model.number="form.phone" :disabled="is_edit" placeholder="请输入电话" maxlength="11" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" :disabled="is_edit" placeholder="请输入邮箱" maxlength="20" />
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <!-- <treeselect
          :disabled="level==2"
          v-model="deptId"
          :options="depts"
          :style="style"
          placeholder="选择部门"
          @select="selectFun"
        /> -->
         <el-select v-model="deptId"  @change="selectFun" :style="style"  :disabled="level==2" placeholder="请选择部门" prop="deptId">
          <el-option
            v-for="(item, index) in depts"
            :key="item.name + index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="岗位" prop="jobId">
        <el-select v-model="jobId" :style="style" placeholder="请先选择岗位">
          <el-option
            v-for="(item, index) in jobs"
            :key="item.name + index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-bottom: 0px;" label="角色" prop="roleIds">
        <el-select v-model="roleIds" :style="style" placeholder="请选择角色">
          <el-option
            v-for="(item, index) in roles"
            :key="item.name + index"
            :label="item.name"
            :value="item.id"
            :disabled="item.level==1"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-radio
          v-for="item in dicts"
          :key="item.id"
          v-model="form.enabled"
          :label="item.value"
        >{{ item.label }}</el-radio>
      </el-form-item>
      <el-form-item label="所属区域" prop="enabled" label-width="80px">
        <city :addr_this="addr_this" :citys="citys" ref="city"></city>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  _deptList,
  _jobList,
  _rolesAll,
  _usersCreate,
  _usersUpdate
} from "@/http/ajax";
import city from "@/components/citys/index.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { Treeselect, city },
  name: "adduser",
  props: {
    is_edit: {
      type: Boolean,
      required: true
    },
    cur_this: {
      type: Object,
      required: null
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入电话号码"));
      } else if (!this.isvalidPhone(value)) {
        callback(new Error("请输入正确的11位手机号码"));
      } else {
        callback();
      }
    };
    return {
      addr_this: this,
      citys: {
        provinceId: "",
        cityId: "",
        districtId: ""
      },
      dicts: [
        { id: 1, label: "启用", value: true },
        { id: 2, label: "禁用", value: false }
      ],
      roleIds: '',
      roles: [],
      loading: false,
      dialog: false,
      deptId: '',
      depts: [],
      style: "width: 184px",
      jobId: '',
      jobs: [],
      form: {
        username: "",
        password: "",
        email: "",
        enabled: true,
        roles: [],
        job: { id: "" },
        dept: { id: "" },
        phone: null
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
        ],
        phone: [{ required: true, trigger: "blur", validator: validPhone }],
        password: [{ required: true, trigger: "blur", message: "请输入密码" }],
        // jobId: [{ required: true, message: "请选择岗位", trigger: "change" }],
        // deptId: [{ required: true, message: "请选择部门", trigger: "change" }],
        // roleIds: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
      isAddr: false,
      level:sessionStorage.level
    };
  },
  watch: {
    roleIds(val) {
      this.checkRole(val);
    }
  },
  methods: {
    checkRole(val) {
      this.isAddr = false;
      this.roles.forEach(el => {
        if(el.id==val){
          if (el.level === 2 || el.level === 3 || el.level === 4) {
              this.isAddr = true;
          }else{
            this.isAddr = false;
          }
        }
      });
    },
    domInit(val) {
      this.dialog = true;
      _deptList(
        {},
        res => {
          this.depts = res.content;
          this.$refs["form"].resetFields();
          if (this.level == 2) {
            this.deptId = this.depts[0].id;
            this.getJobs(this.deptId);
          }
        },
        err => {}
      );
      _rolesAll(
        { level: this.level },
        res => {
          this.$refs["form"].resetFields();
          this.roles = res;
          this.checkRole(val);
        },
        err => {}
      );
    },
    getJobs(id) {
      let data = {
        deptId: id,
        page: 0,
        size: 9999
      };
      _jobList(
        data,
        res => {
          this.jobs = res.content;
        },
        err => {}
      );
    },
    cancel() {
      this.resetForm();
    },
    doSubmit() {
      this.form.dept.id = this.deptId;
      this.form.job.id = this.jobId;
      Object.keys(this.citys).forEach(key => {
        this.form[key] = this.citys[key] || "";
      });
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.deptId) {
            this.$message({
              message: "部门不能为空",
              type: "warning"
            });
          } else if (!this.jobId) {
            this.$message({
              message: "岗位不能为空",
              type: "warning"
            });
          } else if (!this.roleIds) {
            this.$message({
              message: "角色不能为空",
              type: "warning"
            });
          } else if (!this.form.provinceId) {
            this.$message({
              message: "请选择用户所在区域",
              type: "warning"
            });
          } else {
            let user = JSON.parse(sessionStorage.user);
            if (this.level == 2 && this.form.provinceId !== user.provinceId) {
              this.$message({
                message: `您只能添加${user.province.name}的用户`,
                type: "warning"
              });
              return;
            }
            this.loading = true;
            this.form.roles = [];
            const _this = this;
            // this.roleIds.forEach(function(data, index) {
            //   const role = { id: data };
            // });
              _this.form.roles.push({id:_this.roleIds});
            if (this.is_edit) {
              this.doEdit();
            } else this.doAdd();
          }
        } else {
          return false;
        }
      });
    },
    doAdd() {
      _usersCreate(
        this.form,
        res => {
          this.resetForm();
          this.$notify({
            title: "添加成功",
            type: "success",
            duration: 2500
          });
          this.loading = false;
          this.cur_this.getList();
           this.citys = {
              provinceId: 0,
              cityId: 0,
              districtId: 0
            };
            const _this = this.$refs.city;
            _this.dataInit();
        },
        err => {
          this.loading = false;
          console.log(err.response.data.message);
        }
      );
    },
    doEdit() {
      _usersUpdate(
        this.form,
        res => {
          this.resetForm();
          this.$notify({
            title: "修改成功",
            type: "success",
            duration: 2500
          });
          this.loading = false;
          this.cur_this.getList();
        },
        err => {
          this.loading = false;
          // console.log(err.response.data.message);
        }
      );
    },
    resetForm() {
      this.dialog = false;
      this.$refs["form"].resetFields();
      this.deptId = '';
      this.jobId = '';
      this.roleIds = '';
      this.form = {
        username: "",
        email: "",
        enabled: false,
        roles: [],
        job: { id: "" },
        dept: { id: "" },
        phone: null
      };
    },
    selectFun(node) {
      this.jobId = '';
      this.getJobs(node);
    },
    isvalidPhone(str) {
      const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
      return reg.test(str);
    }
  }
};
</script>

<style lang="scss">
</style>
